package api

import (
	"examination-management/api/cmd/config"
	"examination-management/api/handler/request"
	"examination-management/api/pkg"
	pb "examination-management/api/proto"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"time"
)

func CreateStudent(c *gin.Context) {
	var req request.CreateStudentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewExaminationClient(conn)

	student, _ := client.CreateStudent(c, &pb.CreateStudentReq{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	})
	c.JSON(200, student)
}

func LoginStudent(c *gin.Context) {
	var req request.LoginStudentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewExaminationClient(conn)

	student, _ := client.LoginStudent(c, &pb.LoginStudentReq{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	})
	if student.Code != 200 {
		c.JSON(200, student)
		return
	}
	token, _ := jwt2.NewJWT(config.JWT_SELECT_KEY).CreateToken(jwt2.CustomClaims{
		ID: uint(student.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
}

func UpdateStudent(c *gin.Context) {
	var req request.UpdateStudentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewExaminationClient(conn)

	student, _ := client.UpdateStudent(c, &pb.UpdateStudentReq{
		Id:           uint64(c.GetUint("studentId")),
		StudentName:  req.StudentName,
		StudentClass: req.StudentClass,
		College:      req.College,
	})
	c.JSON(200, student)
}
